<script setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

const chartRef = ref(null);

// 格式化时间戳为 YYYY-MM-DD HH:mm 的形式
const formatDateTime = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

onMounted(() => {
  const chart = echarts.init(chartRef.value);

  const fetchDataAndUpdateChart = async () => {
    try {
      const [airTempResponse, soilTempResponse] = await Promise.all([
        axios.get('http://localhost:8085/AirTemperature/tenAirTemperaturedata'),
        axios.get('http://localhost:8085/SoilTemperature/tenSoilTemperaturedata')
      ]);

      const airTempData = airTempResponse.data.map(item => ({
        ...item,
        dataValue: item.dataValue / 10 // 将土壤温度除以10
      }));
      const soilTempData = soilTempResponse.data;

      const timeData = airTempData.map(item => formatDateTime(item.createTime));
      const airTempValues = airTempData.map(item => item.dataValue);
      const soilTempValues = soilTempData.map(item => item.dataValue);

      const option = {
        title: {
          text: '土壤温度与空气温度随时间变化',
          left: 'center',
          textStyle: { color: '#FFFFFF' },
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            const time = params[0].name;
            const airTemp = params[0].data;
            const soilTemp = params[1].data;
            return `${time}<br>空气温度: ${airTemp}°C<br>土壤温度: ${soilTemp}°C`;
          },
        },
        legend: {
          data: ['土壤温度','空气温度'],  // 图例中的名称
          textStyle: {
            color: '#FFFFFF',  // 图例文本颜色
          },
          top: '10%',  // 图例的位置
        },
        xAxis: {
          type: 'category',
          data: timeData,
          axisLabel: { rotate: 45, color: '#FFFFFF' },
          axisLine: { lineStyle: { color: '#FFFFFF' } },
          axisTick: { show: true, lineStyle: { color: '#FFFFFF' } },
        },
        yAxis: {
          type: 'value',
          name: '温度 (°C)',
          axisLabel: { color: '#FFFFFF' },
          axisLine: { lineStyle: { color: '#FFFFFF' } },
          axisTick: { show: true, lineStyle: { color: '#FFFFFF' } },
        },
        series: [
          { name: '空气温度', type: 'line', data: airTempValues, smooth: true, itemStyle: { color: '#33A1FF' }, lineStyle: { width: 2 } },
          { name: '土壤温度', type: 'line', data: soilTempValues, smooth: true, itemStyle: { color: '#FF5733' }, lineStyle: { width: 2 } },
        ],
        grid: { left: '10%', right: '10%', bottom: '10%', top: '20%' },
        dataZoom: [{ type: 'inside', start: 0, end: 100 }],
      };

      chart.setOption(option);
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  };

  fetchDataAndUpdateChart();
  setInterval(fetchDataAndUpdateChart, 300000); // 每5分钟更新一次数据
});
</script>

<template>
  <dv-border-box10>
    <div ref="chartRef" style="width: 430px; height: 210px;margin-left: 20px;margin-top: 10px"></div>
  </dv-border-box10>
</template>

<style scoped>

</style>